var express = require("express");
var router = express.Router();
var { UserModel, GrModel } = require("../db/db");
var Objectid = require("mongodb").ObjectId;
var fs = require("fs");
var path = require("path");
var multer = require("multer");
var upload = multer({ dest: "public/excels" });
var xlsx = require("node-xlsx");

/* GET users listing. */
router.get("/user", async function (req, res, next) {
  if (Object.keys(req.query).length > 0) {
    var data = await UserModel.find(req.query);
    res.send({ data: data });
  } else {
    var data = await UserModel.find({});
    res.send({ data: data });
  }
});
router.get("/gr", async function (req, res, next) {
  if (Object.keys(req.query).length > 0) {
    var data = await GrModel.find(req.query);
    res.send({ data: data });
  } else {
    var data = await GrModel.find({});
    res.send({ data: data });
  }
});
router.post("/user", async function (req, res, next) {
  data = req.body;
  if (data["username"] != "" || data["phone"] != "" || data["pwd"] != "") {
    test = await UserModel.find({ username: data["username"] }).exec();
    if (test.length > 0) {
      res.send({ code: 204, message: "已存在这条数据" });
    } else {
      UserModel.create({
        username: data["username"],
        place: data["place"],
        phone: data["phone"],
        pwd: data["pwd"],
        createTime: data["createTime"],
        recentlylogged: data["recentlylogged"],
        state: data["state"],
      });
      res.send({ code: 200, message: "创建成功" });
    }
  } else {
    res.send({ code: 204, message: "缺少参数" });
  }
});
router.post("/gr", async function (req, res, next) {
  data = req.body;
  if (data["username"] != "" || data["phone"] != "" || data["pwd"] != "") {
    test = await GrModel.find({ username: data["username"] }).exec();
    if (test.length > 0) {
      res.send({ code: 204, message: "已存在这条数据" });
    } else {
      GrModel.create({
        username: data["username"],
        place: data["place"],
        phone: data["phone"],
        pwd: data["pwd"],
        createTime: data["createTime"],
        recentlylogged: data["recentlylogged"],
        state: data["state"],
      });
      res.send({ code: 200, message: "创建成功" });
    }
  } else {
    res.send({ code: 204, message: "缺少参数" });
  }
});

router.delete("/user", async function (req, res) {
  var id = Objectid(req.query.id);
  await UserModel.findByIdAndDelete({ _id: id }, function (err, data) {
    if (!err) {
      res.json({ message: "删除成功", code: 201 });
    }
  });
});
router.delete("/gr", async function (req, res) {
  var id = Objectid(req.query.id);
  await GrModel.findByIdAndDelete({ _id: id }, function (err, data) {
    if (!err) {
      res.json({ message: "删除成功", code: 201 });
    }
  });
});
router.put("/user", async function (req, res) {
  data = req.body;
  var id = Objectid(data["_id"]);
  await UserModel.find({ _id: id }).update({ $set: data });
  res.send({ code: 200 });
});
router.put("/user2", async function (req, res) {
  console.log(req.body)
  // var id = Objectid(data["_id"]);
  await UserModel.updateOne({ '_id': req.body._id }, req.body.state = !req.body.state);
  res.send({ code: 200 });
});
router.put("/gr", async function (req, res) {
  data = req.body;
  var id = Objectid(data["_id"]);
  await GrModel.find({ _id: id }).update({ $set: data });
  res.send({ code: 200 });
});
router.put("/gr2", async function (req, res) {
  data = req.body;
  var id = Objectid(data["_id"]);
  await GrModel.find({ _id: id }).updateOne({ $set: { state: data.state } });
  res.send({ code: 200 });
});
router.post("/user/load", upload.single("file"), async function (req, res) {
  var pash = path.extname(req.file.originalname);
  // console.log(pash);  //打印出来是文件的后缀名
  fs.renameSync(req.file.path, req.file.path + pash, (err) => { });
  // 第一个文件sheet1
  var { data } = xlsx.parse(req.file.path + pash)[0];
  data.splice(0, 1);
  var list = [];
  //定义一个空列表，并且循环列表
  data.forEach((item) => {
    //把数据取出并添加到list列表中,使他形成一个[{},{}]数组包多个对象的形式，数据名必须跟集合里的字段一样
    list.push({
      username: item[0],
      place: item[1],
      phone: item[2],
      pwd: item[3],
      state: item[4],
    });
  });
  //把数据插入到表中
  UserModel.insertMany(list);
  res.json({ code: 200, msg: "批量导入成功" });
});
// 修改会员状态
router.patch('/user/state', async (req, res) => {
  console.log(req.body)
  res.send({
    code: 200,
    msg: '状态修改成功!'
  })
})
module.exports = router;
